
interface IItem {
  func: Function;
  ctx: unknown;
}

export default class EventMgr {

  private constructor() {}
  private static Instance_: EventMgr = null;
  static get Instance() {
    if (!this.Instance_) {
      this.Instance_ = new EventMgr();
    }
    return this.Instance_;
  }

  eventDic: Map<string, Array<IItem>> = new Map();

  on(event: string, func: Function, ctx?: unknown) {
    if (this.eventDic.has(event)) {
      this.eventDic.get(event).push({ func, ctx });
    } else {
      this.eventDic.set(event, [{ func, ctx }]);
    }
  }

  off(event: string, func: Function) {
    if (this.eventDic.has(event)) {
      const index = this.eventDic.get(event).findIndex(i => func === i.func);
      index > -1 && this.eventDic.get(event).splice(index, 1);
    }
  }

  emit(event: string, ...params: unknown[]) {
    if (this.eventDic.has(event)) {
      this.eventDic.get(event).forEach(({ func, ctx }) => {
        //apply方法允许你调用一个具有给定this值的函数，并且params是一个参数数组，它将被展开并传递给func。
        ctx ? func.apply(ctx, params) : func(...params);//三元运算
      });
    }
  }

  clear() {
    console.info("clear EventMgr");
    this.eventDic.clear();
  }
}
